package org.xs.big_event.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xs.big_event.dao.category.Category;
import org.xs.big_event.dao.category.CategoryRepository;
import org.xs.big_event.dao.user.UserRepository;
import org.xs.big_event.service.ICategoryService;
import org.xs.big_event.utils.R;
import org.xs.big_event.utils.ResponseEnum;
import org.xs.big_event.utils.ThreadLocatUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;

@Service
public class CategoryService implements ICategoryService {
    CategoryRepository categoryRepository;
    UserRepository userRepository;
    @Autowired
    public CategoryService(
            CategoryRepository categoryRepository,
            UserRepository userRepository) {
        this.userRepository=userRepository;
        this.categoryRepository = categoryRepository;
    }
    /*
    添加文章类别
      * @param category
      * @return ok
     */
    @Override
    public R add(Category category) {
        //获取当前用户ID
        Integer userId=Integer.valueOf(ThreadLocatUtil.get());
        //查找用户分类
        ArrayList<Category> categoryList=categoryRepository.findAllclassByUser(userId);
        for (Category category1:categoryList) {
            if ((category1.getCategoryName()).equals(category.getCategoryName())) {
                return R.error(ResponseEnum.CATEGORY_EXIST);
            }
        }
        //补充属性
        category.setCreateUser(userId);
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryRepository.save(category);
        return R.ok();
    }

    /*
    获取用户所有文章类别
      * @return ok
     */
    @Override
    public R list() {
        Integer userId=Integer.valueOf(ThreadLocatUtil.get());
        ArrayList categoryList=categoryRepository.findAllclassByUser(userId);
        return R.ok(categoryList);
    }
    /*
    获取文章类别详情
    根据id查看文章类别详情
      * @param id
      * @return ok
     */
    @Override
    public R findail(Integer id){
        Optional<Category> tempCategory=categoryRepository.findail(id);
        if (!tempCategory.isPresent()) {
            return R.error(ResponseEnum.CATEGORY_NOT_EXIST);
        }
        Category category=tempCategory.get();
        return R.ok(category);
    }

    /*
    修改文章类别
      * @param category
      * @return ok
     */
    @Override
    @Transactional
    public R update(Category category) {
        if (category.getId()==null){
            return R.error(ResponseEnum.CATEGORY_NOT_EXIST);
        }
        categoryRepository.updateCategory(
                category.getCategoryName(),
                category.getCategoryAlias(),
                LocalDateTime.now(),
                category.getId());
        return R.ok();
    }

}
